package com.cx.simpleweb.config;

import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.ByteArrayInputStream;
import java.io.IOException;

public class RepeatReadRequest extends HttpServletRequestWrapper {

    private byte[] body;

    public RepeatReadRequest(HttpServletRequest request) throws IOException {
        super (request);
        int size = request.getContentLength ();
        if(size < 0 ){
            size = 0;
        }
        body = new byte[size];
        ServletInputStream inputStream = request.getInputStream ();
        inputStream.read (body,0,size);
    }

    public byte[] getBody() {
        return body;
    }

    /**
     * The default behavior of this method is to return getInputStream()
     * on the wrapped request object.
     */
    @Override
    public ServletInputStream getInputStream() throws IOException {
        ByteArrayInputStream bis = new ByteArrayInputStream(body);
        return new ServletInputStream(){
            @Override
            public int read() throws IOException {
                return bis.read ();
            }
            @Override
            public boolean isFinished() {
                return false;
            }

            @Override
            public boolean isReady() {
                return false;
            }

            @Override
            public void setReadListener(ReadListener readListener) {

            }
        };

    }
}